import 'dart:async';
import 'dart:convert';

import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:star_author/utils/http/http_crypt_util.dart';

import '../utils/http/http_util.dart';
import '../widgets/custom_dialog/loading_controller.dart';

abstract class BaseApi {
  BaseApi(this.context) {
    HttpUtil.dioOptionsConfig(_dio, timeout: 60);

    HttpUtil.dioInterceptors(_dio);
  }

  String _loadingText = '加载中...';

  final Dio _dio = Dio();

  BuildContext context;

  Map<String, dynamic> requestParams = {};

  String getMethod() {
    return HttpUtil.MethodGet;
  }

  String getPath();

  bool isShowLoading() {
    return false;
  }

  bool isErrorToast() {
    return false;
  }

  bool isCatchErrorLogin() {
    return true;
  }

  void setLoadingText(String text) {
    _loadingText = text;
  }

  Future<Response> send({CancelToken? cancelToken}) async {
    if (isShowLoading()) {
      LoadingController.show(context, _loadingText);
    }

    String path;
    if (getPath().startsWith('http')) {
      path = getPath();
    } else {
      path = HttpUtil.getServerPath() + getPath();
    }

    HttpUtil.getRequestParams(
      _dio.options,
      url: getPath(),
      method: getMethod(),
      queryParameters: requestParams,
    );

    if (getMethod() == HttpUtil.MethodGet) {
      requestParams.forEach((key, value) {
        if (path.contains('?')) {
          path += '&$key=$value';
        } else {
          path += '?$key=$value';
        }
      });
    }

    _dio.options.method = getMethod();

    Future<Response> result = _dio.request(path,
        data: jsonEncode(requestParams), cancelToken: cancelToken);

    result.catchError((error) {
      HttpUtil.dioErrorHandle(
        context,
        error,
        isErrorToast(),
        isCatchErrorLogin: isCatchErrorLogin(),
      );
    }).whenComplete(() {
      if (isShowLoading()) LoadingController.complete();
    });

    return result;
  }
}
